package com.ygxsk.carhome.ui.insurance;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.CarRenewalStatus;
import com.ygxsk.carhome.event.EventCarInsuranceMain;
import com.ygxsk.carhome.response.CarInsuranceBean;
import com.ygxsk.carhome.response.CarInsuranceOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.BaseImmersionFragment;
import com.ygxsk.carhome.ui.adapter.CarInsuranceAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CarInsuranceHistoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 * 一键出险 的界面
 */
public class CarInsuranceHistoryFragment extends BaseImmersionFragment {

    @BindView(R.id.refreshLayoutInInsurance)
    SmartRefreshLayout refreshLayoutInInsurance;

    @BindView(R.id.recyclerViewInInsurance)
    RecyclerView recyclerViewInInsurance;

    private ArrayList<CarInsuranceBean> mDataResources = new ArrayList<>();

    private CarInsuranceAdapter carInsuranceAdapter;

    private int pagination_upLoad = Parameterkey.pageNum_default_first;


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM_INDEX = "arg_param_index";
    private static final String ARG_PARAM_TITLE_NAME = "arg_param_title_name";

    // TODO: Rename and change types of parameters
    private String arg_param_index;
    private String arg_param_title_name;

    public CarInsuranceHistoryFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment CarInsuranceFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CarInsuranceHistoryFragment newInstance(String index, String titleName) {

        CarInsuranceHistoryFragment fragment = new CarInsuranceHistoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM_INDEX, index);
        args.putString(ARG_PARAM_TITLE_NAME, titleName);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mFragmentInstance = this;
        mActivityInstance = this.getActivity();

        if (getArguments() != null) {
            arg_param_index = getArguments().getString(ARG_PARAM_INDEX);
            arg_param_title_name = getArguments().getString(ARG_PARAM_TITLE_NAME);
        }

        //列表之内需要向外部广播数据
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initView() {
        super.initView();

        recyclerViewInInsurance.setLayoutManager(new MyLinearLayoutManager(this.getContext()));
        carInsuranceAdapter = new CarInsuranceAdapter(R.layout.insurancelistadapter, mDataResources);
        recyclerViewInInsurance.setAdapter(carInsuranceAdapter);
        carInsuranceAdapter.notifyDataSetChanged();

        carInsuranceAdapter.setOnItemClickListener(new com.chad.library.adapter.base.listener.OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CarInsuranceBean carInsuranceBean = (CarInsuranceBean) adapter.getItem(position);

                if (carInsuranceBean != null) {

                    Bundle extra_bundle = new Bundle();

                    extra_bundle.putParcelable(ExtraKey.EXTRA_CAR_INSURANCE_LIST_ITEM_BEAN, carInsuranceBean);

                    ActivityUtils.startActivity(extra_bundle, CarInsuranceDetailActivity.class);

                }

            }
        });


        carInsuranceAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CarInsuranceBean carInsuranceBean = (CarInsuranceBean) adapter.getItem(position);

                switch (view.getId()) {

                    case R.id.textViewPersonPhoneValueInsurance: {//拨打电话号码 内容；

                        if (carInsuranceBean != null) {

                            clickButton_toCallPhone(CarInsuranceHistoryFragment.this.getActivity(), carInsuranceBean.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_10.getIndex());

                        }

                        break;
                    }

//                    case R.id.roundTextViewViewTakeOrderInsurance: {//接单
//
//                        if (carInsuranceBean != null) {
//
//                            CommUtils.checkDialog(mAlertView);
//                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
//                                    StringUtils.getString(R.string.submit_carrenewal_takeorder_message),//提示内容 确定接单
//                                    StringUtils.getString(R.string.clearcachecancel), //取消
//                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
//                                    null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
//                                @Override
//                                public void onItemClick(Object o, int position) {
//
//                                    if (position != AlertView.CANCELPOSITION) {
//
//                                        method_gainTakeOrderSubmitInfo_upLoad(carInsuranceBean.getLossAdviceId());
//
//                                    }
//
//                                }
//                            });
//
//                            mAlertView.setCancelable(true);
//                            mAlertView.show();
//
//                        }
//
//                        break;
//                    }

//                    case R.id.roundTextViewViewCompleteOrderInsurance: {//完成
//
//                        if (carInsuranceBean != null) {
//
//                            CommUtils.checkDialog(mAlertView);
//                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
//                                    StringUtils.getString(R.string.submit_carrenewal_completeorder_message),//提示内容 确定审核通过
//                                    StringUtils.getString(R.string.clearcachecancel), //取消
//                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
//                                    null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
//                                @Override
//                                public void onItemClick(Object o, int position) {
//
//                                    if (position != AlertView.CANCELPOSITION) {
//
//                                        method_gainCompleteSubmitInfo_upLoad(carInsuranceBean.getLossAdviceId());
//
//                                    }
//
//                                }
//                            });
//
//                            mAlertView.setCancelable(true);
//                            mAlertView.show();
//
//                        }
//
//                        break;
//                    }

                    default:
                        break;
                }

            }
        });


        refreshLayoutInInsurance.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {


            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        pagination_upLoad = Parameterkey.pageNum_default_first;

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        getServerDatas();

                        refreshLayout.finishRefresh();
                    }
                });

            }


            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        getServerDatas();

                        refreshLayout.finishLoadMore();

                    }
                });

            }

        });

    }

    @Override
    protected void initData() {
        super.initData();

        gainDatas();

    }

    @Override
    protected void gainDatas() {

        //是否有其他需要调用接口的地方；
        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (carInsuranceAdapter != null) {
            carInsuranceAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {

            //是否有其他的执行逻辑？
            netWorkError();
            setEnableLoadmore(refreshLayoutInInsurance, false);

        }


    }


    //完成 按钮
    private void method_gainCompleteSubmitInfo_upLoad(Integer _ids) {

        //第一种方式
        //Integer[] idsArray = new Integer[]{Integer.parseInt(_ids)};
        //第二种方式
        Integer[] idsArray = new Integer[]{_ids};

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.ids, idsArray);

//        map.put(Parameterkey.status, ConsignStatus.STATUS_HAS_VERIFY.getIndex());//2:已审核 即审核通过状态

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_COMPLETERENEWALINSURANCE_URL);//
        addLogUpLoadInfo.setUrlPath(ApiService.completeRenewalInsurance_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .completeLossAdvice(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CarRenewalFragment.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        //通知主页列表刷新
                        EventCarInsuranceMain eventCarInsuranceMain = new EventCarInsuranceMain();
                        eventCarInsuranceMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_MAIN_LIST);
                        EventBus.getDefault().post(eventCarInsuranceMain);

                        methodSubmitSuccess(CarInsuranceHistoryFragment.this.getActivity(), null);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });
    }


    //接单 按钮
    private void method_gainTakeOrderSubmitInfo_upLoad(Integer _ids) {

        //传递参数的形式变成了如下格式：
//        {
//            "ids":["9"]
//        }

//        ArrayList<String> idsList = new ArrayList<>();
//        idsList.add(_ids);
        Integer[] idsArray = new Integer[]{_ids};
        //idsArray[0] = _ids;

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.ids, idsArray);//

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_RECEIVERENEWALINSURANCE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.receiveRenewalInsurance_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .receiveLossAdvice(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CarRenewalFragment.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        //通知主页列表刷新
                        EventCarInsuranceMain eventCarInsuranceMain = new EventCarInsuranceMain();
                        eventCarInsuranceMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_MAIN_LIST);
                        EventBus.getDefault().post(eventCarInsuranceMain);

                        methodSubmitSuccess(CarInsuranceHistoryFragment.this.getActivity(), null);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //
                    }
                });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadCarInsurance(EventCarInsuranceMain eventCarInsuranceMain) {

        if (eventCarInsuranceMain != null) {

            if (eventCarInsuranceMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_MAIN_LIST) {

                pagination_upLoad = Parameterkey.pageNum_default_first;

                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

//                if (consignMainAdapter != null) {
//                    consignMainAdapter.notifyDataSetChanged();
//                }

                getServerDatas();

            }

        }

    }

    private void getServerDatas() {

        HashMap<String, Object> hashMapParameter = new HashMap<>();
        hashMapParameter.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        hashMapParameter.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        hashMapParameter.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字


//        0=未接单   1=已接单    2=已完成

        // status  0未接单  1已接单   2已完成
//            public enum CarRenewalStatus {
//            status  0未接单  1已接单   2已完成
//                    STATUS_NOT_TAKEORDER("0", "未接单"),
//                    STATUS_HAS_TAKEORDER("1", "已接单"),
//                    STATUS_HAS_COMPLETE("2", "已完成");

        StringBuffer stringBuffer = new StringBuffer();
        //已完成
        stringBuffer.append(CarRenewalStatus.STATUS_HAS_COMPLETE.getIndex().trim());

        hashMapParameter.put(Parameterkey.statusStr, stringBuffer.toString());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETLOSSADVICELISTPAGE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getLossAdviceListPage_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(hashMapParameter);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getLossAdviceListPage(RequestBody.create(JSON.toJSONString(hashMapParameter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                //.compose(mActivityInstance.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CarInsuranceOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "handlerSomeThingNotSuccessDataForItSelf");

                        methodNotSuccessData(what_method, serverCode, serverMessage);

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        loadingGone();

                        if (refreshLayoutInInsurance != null) {
                            refreshLayoutInInsurance.setEnableLoadMore(true);
                        }
                    }
                }).subscribe(new Consumer<CarInsuranceOutSide>() {
                    @Override
                    public void accept(CarInsuranceOutSide carInsuranceOutSide) throws Throwable {

                        if (carInsuranceOutSide != null) {

                            ArrayList<CarInsuranceBean> currentDatas = carInsuranceOutSide.getDataList();

                            if (currentDatas != null && !currentDatas.isEmpty()) {
                                if (mDataResources != null) {
                                    mDataResources.addAll(currentDatas);
                                }
                            }
                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            //同时禁用加载更多；
                            if (refreshLayoutInInsurance != null) {
                                refreshLayoutInInsurance.setEnableLoadMore(false);
                            }
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }


                        if (carInsuranceAdapter != null) {
                            carInsuranceAdapter.notifyDataSetChanged();
                        }

                        //给分页值
                        pagination_upLoad = carInsuranceOutSide.getNextPagination();

                        //对列表改造：
                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
                            setFinishLoadMoreWithNoMoreData(refreshLayoutInInsurance, true);
                        } else {
                            setEnableLoadmore(refreshLayoutInInsurance, true);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.WHAT_GETLOSSADVICELISTPAGE_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

                    if (refreshLayoutInInsurance != null) {
                        refreshLayoutInInsurance.setEnableLoadMore(false);
                    }

                    CommUtils.checkCurrently(mFragmentInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (carInsuranceAdapter != null) {
            carInsuranceAdapter.notifyDataSetChanged();
            carInsuranceAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_insurance;
    }

    @Override
    public void onClickNodata(View view) {

        gainDatas();

    }
}